import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'
import { isLogin } from 'utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/cate',
    name: 'cate',
    component: () => import('views/Cate'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/cart',
    name: 'cart',
    component: () => import('views/Cart'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/mine',
    name: 'mine',
    component: () => import('views/Mine'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/itemLists/:cate_id',
    name: 'itemLists',
    component: () => import('views/ItemLists'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/detail',
    name: 'detail',
    component: () => import('views/Detail'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('views/Login'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('views/Order'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactLists',
    name: 'contactLists',
    component: () => import('views/ContactLists'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactAdd',
    name: 'contactAdd',
    component: () => import('views/AddContact'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactEdit',
    name: 'contactEdit',
    component: () => import('views/EditContact'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('views/Search'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/searchLists',
    name: 'searchLists',
    component: () => import('views/SearchLists'),
    meta: {
      needLogin: false
    }
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 判断 目标路由是否需要登录
  if (to.meta.needLogin) {
    // 判断是否登录
    if (isLogin()) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.fullPath
        }
      })
    }
  } else {
    next()
  }
})

export default router
